﻿using Abp;
using Abp.Application.Services;
using FwProject.Manager;
using FwProject.ShopApplication;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Abp.ObjectMapping;
using FwProject.ShoppingMall.EventAdvertising;
using Abp.Domain.Repositories;
using X.PagedList;
using System.Linq;
using AutoMapper.QueryableExtensions;
using Abp.AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using FwProject.PublicService;
using Abp.Authorization;

namespace FwProject.EventAdvertising.Dto
{
    /// <summary>
    ///  商城优惠券管理
    /// </summary>
    [AbpAuthorize]
    public class ShopCouponAppService : FwProjectAppServiceBase, IShopCouponAppService
    {
        private readonly ShopCouponManager _shopCouponManager;
        private readonly IRepository<ShopCoupon, Guid> _shopCouponRepository;
        private readonly IRepository<ShopUserCoupon, Guid> _shopUserCouponRepository;
        private Abp.IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }

        private readonly IConfigurationRoot _appConfiguration;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="shopCouponManager"></param>
        /// <param name="shopCouponRepository"></param>
        /// <param name="shopUserCouponRepository"></param>
        public ShopCouponAppService(ShopCouponManager shopCouponManager, IRepository<ShopCoupon, Guid> shopCouponRepository, IRepository<ShopUserCoupon, Guid> shopUserCouponRepository,IHostingEnvironment hostingEnvironment)
        {

            _shopCouponManager = shopCouponManager;
            _guid = SequentialGuidGenerator.Instance;
            _map = NullObjectMapper.Instance;
            _shopCouponRepository = shopCouponRepository;
            _shopUserCouponRepository = shopUserCouponRepository;

            _appConfiguration = hostingEnvironment.GetAppConfiguration();
        }
        /// <summary>
        /// 创建一个优惠券
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Guid> CreateShopAdLocation(ShopCouponInput Input)
        {
            var model = Input.MapTo<ShopCoupon>();
            model.Id = _guid.Create();

            string FileTempPath = _appConfiguration["FileServicePath:TempCoupon"];
            string FileSavaPath = _appConfiguration["FileServicePath:SavaCoupon:SavaFilePath"];
            var path = SaveFile(Input.CouponPic, FileTempPath, FileSavaPath, $"{DateTime.Now.ToString("yyyyMMdd")}/");
            model.CouponPic = _appConfiguration["FileServicePath:SavaCoupon:Virtual"] + path;

            return await _shopCouponManager.CreateShopCoupon(model);

        }

        /// <summary>
        /// 获取一个优惠券
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ShopCouponDto> GetByIdShopCoupon(Guid Id)
        {
            var model =await _shopCouponRepository.GetAsync(Id);
            return  model.MapTo<ShopCouponDto>();
         
        }

        /// <summary>
        /// 修改一个优惠券
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task EditShopAdLocation(Guid Id, ShopCouponInput Input)
        {
            var model = _shopCouponRepository.Get(Id);
            model = _map.Map(Input, model);
            var original = "";
            if (!model.CouponPic.Contains("uploads"))
            {
                if (!string.IsNullOrEmpty(model.CouponPic))
                {
                    var l = model.CouponPic.Split('/');
                    original = l[l.Length - 1];
                }

                string FileTempPath = _appConfiguration["FileServicePath:TempCoupon"];
                string FileSavaPath = _appConfiguration["FileServicePath:SavaCoupon:SavaFilePath"];
                var path = SaveFile(Input.CouponPic, FileTempPath, FileSavaPath, $"{DateTime.Now.ToString("yyyyMMdd")}/", original);
                model.CouponPic = _appConfiguration["FileServicePath:SavaCoupon:Virtual"] + path;

            }

            await _shopCouponManager.UpdateShopCoupon(model);
        }
        /// <summary>
        /// 删除一个优惠券
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task DeleteAdLocation(Guid Id)
        {
            var model = _shopCouponRepository.Get(Id);
            await _shopCouponManager.DeleteShopCoupon(model);
        }
        /// <summary>
        ///  分页查询优惠券
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="pageSize">条数</param>
        /// <param name="CouponTitile">优惠券名称</param>
        /// <param name="beginTime">开始使用时间</param>
        /// <param name="endTime">结束使用时间</param>
        /// <param name="coupontype">优惠券类别</param>
        /// <param name="usecoupon">优惠券使用范围</param>
        /// <returns></returns>
        public async Task<IPagedList<ShopCouponDto>> GetPageList(int page, int pageSize, string CouponTitile, DateTime? beginTime, DateTime? endTime, CouponType? coupontype, UseCoupon? usecoupon)
        {

            var list = _shopCouponRepository.GetAll();
            if (!string.IsNullOrEmpty(CouponTitile))
                list = list.Where(o => o.CouponTitile.Contains(CouponTitile));

            if (beginTime != null)
                list = list.Where(o => o.UseBeginTime >= beginTime);

            if (endTime != null)
                list = list.Where(o => o.UseEndTime <= endTime.Value.AddHours(24));

            if (coupontype != null)
                list = list.Where(o => o.CouponType == coupontype);

            if (usecoupon != null)
                list = list.Where(o => o.UseCoupon == usecoupon);

            return await list.OrderByDescending(o => o.CreationTime).ProjectTo<ShopCouponDto>().ToPagedListAsync(page, pageSize);
        }

        /// <summary>
        /// 获取用户优惠券信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<LayerDataBaseDto> GetShopCouponLayerDataAsync(int page, int limit)
        {
            var query = _shopCouponRepository.GetAll().OrderByDescending(o=>o.CreationTime).GroupJoin(_shopUserCouponRepository.GetAll(), i => i.Id, j => j.ShopCouponId, (i, j) => new ShopCouponOutputDto
            {
                Id = i.Id,
                CouponPrice = i.CouponPrice,
                CouponTitile = i.CouponTitile,
                CouponType = i.CouponType,
                UseBeginTime = i.UseBeginTime,
                UseEndTime = i.UseEndTime,
                UseCoupon = i.UseCoupon,
                CouponCount = j.Count(),
                UseCount = j.Where(o => o.UseStatus == UseStatus.Used).Count()
            });

            var pagelist = await query.ToPagedListAsync(page, limit);

            LayerDataBaseDto dto = new LayerDataBaseDto();
            dto.Data = pagelist;
            dto.Count = pagelist.TotalItemCount;
            return dto;
        }
    }
}
